package com.light.gulimall.product.exception;


import com.light.common.enums.ExceptionEnum;
import com.light.common.utils.R;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

@RestControllerAdvice
public class GulimallProductExceptionHandler {


    @ExceptionHandler(value = Exception.class)
    public R handlerExp(Exception e){
        if (e instanceof MethodArgumentNotValidException){
            MethodArgumentNotValidException validException = (MethodArgumentNotValidException) e;
            BindingResult bindingResult = validException.getBindingResult();
            if (bindingResult.hasErrors()) {
                Map<String,String> map = new HashMap<>();
                for (FieldError fieldError : bindingResult.getFieldErrors()) {
                    String field = fieldError.getField();
                    String message = fieldError.getDefaultMessage();
                    map.put(field,message);
                }
                return R.error(ExceptionEnum.VAILD_EXCEPTION.getCode(),ExceptionEnum.VAILD_EXCEPTION.getValue()).put("data",map);
            }
        }
        return R.error(ExceptionEnum.UNKNOW_EXCEPTION.getCode(), ExceptionEnum.UNKNOW_EXCEPTION.getValue());
    }

}
